import React, { useReducer } from "react";

const QuotationContext = React.createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "add_data":
      return [...state, action.payload.newData];
    case "edit_data":
      // console.log("计算----", action.payload.value);
      // return action.payload.value;
      return state.map((item, index) => {
        return index == action.payload.key ? action.payload.value : item;
      });
    case "delete_data":
      return state.filter((item, index) => index !== action.payload.index);
    default:
      return state;
  }
};

let initData = [
  {
    type: "商品1",
    detail: {
      specs: {
        shape: [1, "圆形"],
        length: ["1", 2],
        width: ["1", 2],
        radius: ["1", 2],
      },
      basePlate: {
        category: [0, "锌"],
        thickness: ["1", 2],
        type: [0, "任意型号"],
      },
      shroudPlate: {
        category: [0, "锌"],
        thickness: ["1", 2],
        type: [0, "任意型号"],
      },
      amount: "",
    },
  },
  // {
  //   type: "铜钢",
  //   detail: {
  //     specs: {
  //       shape: 1,
  //       radius: ["0", 0],
  //       length: ["0", 0],
  //       width: ["0", 0],
  //     },
  //     length: ["0", 0],
  //     width: ["0", 0],
  //     basePlate: { category: [0, "钢"], thickness: ["0", 0], type: 0 },
  //     shroudPlate: { category: [2, "铜"], thickness: ["0", 0], type: 0 },
  //     amount: "0",
  //   },
  // },
];

export const QuotationProvider = ({ children }) => {
  const [quotationData, dispatch] = useReducer(dataReducer, initData);
  // console.log("initQuotationData---", quotationData);

  const addData = (newData) => {
    dispatch({ type: "add_data", payload: { newData } });
  };

  const editData = (key, value) => {
    dispatch({
      type: "edit_data",
      payload: { key, value },
    });
  };

  const deleteGoods = (index) => {
    dispatch({
      type: "delete_data",
      payload: { index: index },
    });
  };

  return (
    <QuotationContext.Provider
      value={{ quotationData: quotationData, addData, editData, deleteGoods }}
    >
      {children}
    </QuotationContext.Provider>
  );
};

export default QuotationContext;
// import createContext from "./createContext";

// const dataReducer = (state, action) => {
//   switch (action.type) {
//     case "add_data":
//       console.log("lllll------------", state.length);
//       return [...state];

//     default:
//       return state;
//   }
// };

// const addDataCard = (dispatch) => {
//   return (value) => {
//     dispatch({ type: "add_data", payload: value });
//   };
// };

// export const { Context, Provider } = createContext(
//   dataReducer,
//   { addDataCard },
//   [
//     { type: "铝钢", detail: {} },
//     { type: "铜钢", detail: {} },
//   ]
// );
